package dao

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

type LangDao interface {
	AddLangRecord(language Language) error
	FindLangByUserId(ctx *gin.Context, id string) (string, error)
	UpdateLangByUserId(ctx *gin.Context, lang Language) error
}

type GormLangDao struct {
	db *gorm.DB
}

func (g GormLangDao) UpdateLangByUserId(ctx *gin.Context, lang Language) error {
	id, _ := g.FindLangByUserId(ctx, lang.UserId)
	if id != "" {
		// 存在则更新 lang_id
		if tx := g.db.WithContext(ctx).
			Model(&Language{}).
			Where("user_id = ?", lang.UserId).
			Update("lang_id", lang.LangID); tx.RowsAffected == 0 {
			return tx.Error
		}
		return nil
	}
	// 不存在则保存新记录
	if tx := g.db.WithContext(ctx).Save(&lang); tx.RowsAffected == 0 {
		zap.S().Errorf("更新语种日志失败:%s", tx.Error)
		return tx.Error
	}
	return nil
}

func (g GormLangDao) FindLangByUserId(ctx *gin.Context, id string) (string, error) {
	var lang *Language
	if rs := g.db.WithContext(ctx).Where("user_id = ?", id).Find(&lang); rs.RowsAffected == 0 {
		return "", rs.Error
	}
	return lang.LangID, nil
}

func (g GormLangDao) AddLangRecord(language Language) error {
	if tx := g.db.Save(&language); tx.Error != nil {
		zap.S().Errorf("创建语种记录失败:%s", tx.Error)
		return tx.Error
	}
	return nil
}

func NewLangDao(db *gorm.DB) LangDao {
	return &GormLangDao{db: db}
}

type Language struct {
	ID     uint   `gorm:"primaryKey;autoIncrement"`
	LangID string `gorm:"column:lang_id;type:varchar(20);not null" json:"lang_id"`
	UserId string `gorm:"column:user_id;type:varchar(20);not null"json:"user_id"`
}

func (Language) TableName() string {
	return "lang_logs"
}
